package com.ang.juc.nt.list;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;
import java.util.stream.IntStream;

public class CollationsTest {

    public static void main(String[] args) throws InterruptedException {
//        test1();
//        test2();
        test3();
    }

    /**
     * 不安全
     * 可能会报异常，比如数组下标越界
     * 也可能size不够
     */
    public static void test1() throws InterruptedException {
        List<Integer> list = new ArrayList<>();

        List<Thread> lt = new ArrayList<>();

        IntStream.range(0, 10).forEach(i->{
            Thread thread = new Thread(() -> {
                IntStream.range(0,100).forEach(j->{
                    list.add(1);
                });
            });

            thread.start();

            lt.add(thread);
        });

        for (Thread thread : lt) {
            thread.join();
        }

        System.out.println("size:" + list.size());
    }

    //Vector
    public static void test2() throws InterruptedException {
        List<Integer> list = new Vector<>();

        List<Thread> lt = new ArrayList<>();

        IntStream.range(0, 10).forEach(i->{
            Thread thread = new Thread(() -> {
                IntStream.range(0,100).forEach(j->{
                    list.add(1);
                });
            });

            thread.start();

            lt.add(thread);
        });

        for (Thread thread : lt) {
            thread.join();
        }

        System.out.println("size:" + list.size());
    }

    //Collations
    public static void test3() throws InterruptedException {
        List<Integer> list = Collections.synchronizedList(new ArrayList<>());

        List<Thread> lt = new ArrayList<>();

        IntStream.range(0, 10).forEach(i->{
            Thread thread = new Thread(() -> {
                IntStream.range(0,100).forEach(j->{
                    list.add(1);
                });
            });

            thread.start();

            lt.add(thread);
        });

        for (Thread thread : lt) {
            thread.join();
        }

        System.out.println("size:" + list.size());
    }
}
